<template>
    <popup ref="popupRef" :title="popupTitle" width="800px" @confirm="handleConfirm" :async="true" @close="popupClose">
        <div class="pr-8">
            <el-form ref="formAdd" :model="formData" label-width="120px" :rules="formRules">
                <el-form-item label="规格/单位" prop="name">
                    <div class="w-80">
                        <el-input v-model="formData.name" placeholder="请输入" type="text" maxlength="30" show-word-limit clearable />
                    </div>
                </el-form-item>
                <el-form-item label="售卖金额（元）" prop="price">
                    <div class="w-80">
                        <el-input v-model="formData.price" type="number" placeholder="请输入" maxlength="15" show-word-limit clearable />
                    </div>
                </el-form-item>
                <el-form-item label="是否参与补贴" prop="has_subsidy">
                    <div class="w-80">
                        <el-radio-group v-model="formData.has_subsidy">
                            <el-radio :label="1">是</el-radio>
                            <el-radio :label="0">否</el-radio>
                        </el-radio-group>
                    </div>
                </el-form-item>
                <el-form-item v-if="formData.has_subsidy == 1" label="补贴方式" prop="subsidy_type">
                    <div class="w-80">
                        <el-radio-group v-model="formData.subsidy_type">
                            <el-radio :label="1">直接补贴</el-radio>
                            <el-radio :label="2">根据支付金额返点（%）</el-radio>
                        </el-radio-group>
                    </div>
                </el-form-item>
                <el-form-item v-if="formData.has_subsidy == 1 && formData.subsidy_type == 1" label="补贴金额（元）" prop="subsidy_money">
                    <div class="w-80">
                        <el-input-number controls-position="right" v-model="formData.subsidy_money" :step="1" :precision="0" :disabled="!formData.price" placeholder="请输入补贴金额（元）" type="text" maxlength="15" show-word-limit clearable />
                    </div>
                </el-form-item>
                <el-form-item v-if="formData.has_subsidy == 1 && formData.subsidy_type == 2" label="补贴金额（%）" prop="subsidy_num">
                    <div class="w-80">
                        <el-input-number controls-position="right" v-model="formData.subsidy_num" :max="100" placeholder="请输入补贴金额（%）" type="text" maxlength="15" show-word-limit clearable />
                    </div>
                </el-form-item>
            </el-form>
        </div>
    </popup>
</template>
<script lang="ts" setup>
	import Popup from '@/components/popup/index.vue'
	import type { FormInstance, FormRules } from 'element-plus'
	import feedback from '@/utils/feedback'
	const formAdd = shallowRef<FormInstance>()
	const props = defineProps({
		show: {
			type: Boolean,
			required: true
		},
		// value: {
		// 	type: Object,
		// 	required: true
		// }
	})

	const emit = defineEmits<{
		(event: 'update:show', value: boolean): void
		(event: 'confirm', value: any): void
	}>()

	const popupTitle = computed(() => {
		return `新增/编辑产品规格`
	})

	const formData:any = reactive({
		id: 0,
        name: '',
        price: 1,
        has_subsidy: 0,
        subsidy_type: '',
        subsidy_money: '',
        subsidy_num: '',
	})
	
	const popupRef = shallowRef<InstanceType<typeof Popup>>()

    const validatePrice = (rule: any, value: number, callback: Function) => {
        if (value <= 0) {
            callback(new Error('售卖金额必须大于零'));
        } else {
            callback();
        }
    }
	const formRules: FormRules = {
        name: [{required: true,message: '请填写规格/单位'}],
        price: [
            { required: true, message: '请填写售卖金额（元）' },
            { validator: validatePrice, trigger: 'blur' }
        ],
        subsidy_type: [{required: true,message: '请选择补贴方式'}],
        subsidy_money: [{required: true,message: '请填写补贴金额（元）'}],
        subsidy_num: [{required: true,message: '请填写补贴金额（%）'}],
	}
    
    
    const edit_data = (data?:any) => {
        if (data) {
            Object.keys(formData).forEach((key)=>{
                formData[key] = data[key]
            })
        } else {
            formAdd.value?.resetFields()
            formData.id = 0;
            formData.name = '';
            formData.price = '';
            formData.has_subsidy = 0;
            formData.subsidy_type = '',
            formData.subsidy_money = '';
            formData.subsidy_num = '';
        }
       
    }
    // 使用 defineExpose 暴露方法
    defineExpose({
        edit_data,
    });

	const handleConfirm = async () => {
		await formAdd.value?.validate()
        if (formData.price <=0) {
            feedback.msgWarning('售卖金额必须大于0')
            return false;
        }
        if (formData.subsidy_money >= formData.price) {
            feedback.msgWarning('补贴金额不能大于等于售卖金额')
            return false;
        }
        console.log(formData)
		emit('confirm', formData)
	}

	const popupClose = () => {
		emit('update:show', false)
		formAdd.value?.resetFields()
	}

	watch(
		() => props.show,
		(val) => {
			if (val) {
				popupRef.value?.open()
			} else {
				popupRef.value?.close()
			}
		}
	)
</script>
